#!/usr/bin/env python3
import random
import re

import requests
from datetime import datetime
import os.path
import time

import json

import config

from db_helper import DbHelper
from http_helper import HttpHelper
from param_model import ParamModel

http = HttpHelper()
db = DbHelper()
param = ParamModel()

valid_club_ids = [10727, 8474]
MAX_ACT_PER_DAY = len(valid_club_ids) * 8
today_act_count = 0
WEEKDAYS = ['一', '二', '三', '四', '五', '六', '日']
# ACT_NAMES = ['弄个小活动', '快乐一小时', '热身热身热身', '休闲一小时', '放松60分钟', '快乐下午茶', '午后微汗局',
#              '一起流汗', '牛马的快乐', '包球/新手友好', '拉练快上车', '每天进步一点点']
ACT_NAMES = ['建羽打卡场', '站桩娱乐局', '养生局/新人友好', '赛前热身', '内部活动非请勿入', '再不打球就冷了', '快乐每一天',
             '自由挥拍', '弄个小活动', '快乐一小时', '热身热身热身', '休闲一小时', '放松60分钟', '快乐下午茶', '午后微汗局',
             '一起流汗', '牛马的快乐', '包球/新手友好', '拉练快上车', '每天进步一点点']

creator_token = ''
player_tokens = []


def __fetch__(url):
    # 设置自定义请求头
    headers = {
        'Accept': '*/*',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept_Language': 'zh-CN,zh;q=0.9',
        'Content-Type': 'application/json',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 MicroMessenger/WIFI MiniProgramEnv/Windows WindowsWechat',
        'xweb_xhr': '1',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'cross-site',
    }

    try:
        # print(f'正在抓取第{page_no}页数据，每页数据{page_size}条')
        # 发送GET请求
        response = requests.get(url, headers=headers)

        # 检查响应状态码
        if response.status_code == 200:
            return response
        else:
            print(f"请求失败，状态码: {response.status_code}")
            return None

    except requests.exceptions.RequestException as e:
        print(f"请求发生错误: {e}")
        return None
    except json.JSONDecodeError as e:
        print(f"JSON解析错误: {e}")
        return None

def assign_temp_admin():
    acts = http.fetch_club_activities(config.HY_CLUB_ID)['records']
    for act in acts:
        if act['activityAddress'] == '康城羽毛球馆' and (act['startTime'] == '12:00' or act['startTime'] == '14:00'):
            print('康城下午场活动：', act['id'])
            admins = http.fetch_temp_admin(act['id'])
            if not isinstance(admins, list):
                # 未设置管理员时此处不会返回列表
                ret = http.add_temp_admin(act_id=act['id'], member_id_list=[2990797])
                print('为活动设置临时管理员......', ret)
                # print('add admin result:::::::::', ret)
        elif act['activityAddress'] == '209玉泉营羽毛球馆' or (act['activityAddress'] == '康城羽毛球馆' and act['startTime'] == '18:00'):
            admins = http.fetch_temp_admin(act['id'])
            if not isinstance(admins, list):
                # 未设置管理员时此处不会返回列表
                ret = http.add_temp_admin(act_id=act['id'], member_id_list=[2771390, 2675656])
                print('为活动设置临时管理员......', ret)
        time.sleep(3)

def confirm_account():
    global player_tokens
    # 检查所有账号的token过期情况d
    accounts = db.get_user_accounts()
    for account in accounts:
        print('user:', account.to_dict())
        data = account.to_dict()
        last_update = data['last_update']
        expired = False

        # print("时间差:", datetime.now().timestamp() - last_update.timestamp())
        if last_update is not None and last_update.timestamp() - datetime.now().timestamp() > config.TOKEN_EXP_SECONDS:
            expired = True

        access_token = data['access_token']
        if access_token is None or expired:
            access_token = http.login_in(data['phone'], data['password'])
            print('phone:', data['phone'], access_token)
            db.update_account_account(data['phone'], access_token)
            # 等待10秒再处理下一个账号
            time.sleep(10)
        player_tokens.append(access_token)
        # if data['member_name'] == '小伙伴':
        #     http.set_flash_token(access_token)
        #     ret = http.join_club(8474)
        #     print('join club result:::::::::', ret)

    # 获取管理账号
    admin = db.get_admin_account()
    if admin is None:
        print('Admin account not found, exit.')
    else:
        data = admin.to_dict()
        access_token = data['access_token']
        if data['last_update'] is None or datetime.now().timestamp() - data[
            'last_update'].timestamp() > config.TOKEN_EXP_SECONDS:
            # token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjdXN0b21QYXJhbWV0ZXIiOiJxd2VyMTIzNCIsInVzZXJJZCI6ODM1MjY1LCJleHAiOjE3NjE1MzkwMzZ9.9f-ucoi9of2_kmZu0i6184eAd2kZ_0a02OPvx7XiKbc'
            access_token = http.login_in(data['phone'], data['password'])
            db.update_account_account(data['phone'], access_token)
            # token = 'token'
        # 为http接口设置管理员token
        global creator_token
        creator_token = access_token
        http.set_flash_token(access_token)
        # ret = http.user_detail()
        # print('login result:', ret)

# def query_act(act_id, access_token):
#     url = f'https://flash.flashxsport.com/flash/activity/detail?activityId={act_id}&latitude=&longitude='
#     return fetch_flashx(url,)

def query_captcha(phone):
    url = 'http://sms.szfangmm.com:3000/api/smslist?token=szNYWLZhVv4Qvn9g4Vxfjd'
    resp = __fetch__(url)
    if resp is None:
        return None
    sms_list = resp.json()
    for sms in sms_list:
        # if sms['simnum'][0:2] == phone[0:2] and sms['simnum'][5:] == phone[5:] and '闪动' in sms['content']:
        # print(sms['simnum'][0:2] == phone[0:2], sms['simnum'][6:] == phone[7:], '闪动' in sms['content'])
        if sms['simnum'][0:2] == phone[0:2] and sms['simnum'][6:] == phone[7:] and '闪动' in sms['content']:
            match = re.search(r'\b\d{6}\b', sms['content'])
            # print('match:', match.group())
            return None if match is None else match.group(0)

    return None


if __name__ == "__main__":

    # query_captcha('17000001560')

    confirm_account()
    # admin = db.get_admin_account()
    # admin_token = admin.access_token

    loop_count = 1
    while True:
        phone = db.get_one_phone_number()
        if phone is None:
            print('手机号已用完，注册结束。。。。。。')
            break
        # phone = '17695498849'
        print(f'正在进行用户注册，当前号码：{phone}, 当前轮次：{loop_count}')

        # token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjdXN0b21QYXJhbWV0ZXIiOiJxd2VyMTIzNCIsInVzZXJJZCI6NDg3MDI0OCwiZXhwIjoxNzYyMTY2MjY5fQ.uwuVE9l8xxNHQGvRTagAE2bBg-dgyn3B-Y9fptWQ-Ew'
        resp = http.get_sms_code(phone)

        if '发送成功' not in resp:
            if '发送失败' in resp['message']:
                print(f'短信验证码发送失败，手机号{phone}不可用')
                db.update_phone_number(phone, 0)
                continue
            elif '请求频繁' in resp['message']:
                time.sleep(60)
                continue
        print('resp is:', resp)

        # while resp['code'] == 500:
        #     print('获取验证码出错，一分钟后重试：', resp['message'])
        #     resp = http.get_sms_code(phone)
        print('等待30秒查询验证码')
        time.sleep(30)
        code = query_captcha(phone)
        retry_count = 0
        is_ok = True
        while code is None:
            retry_count = retry_count + 1
            if retry_count > 5:
                print('等待多次仍未收到验证码，进入下一个号码')
                is_ok = False
                break
            print('没收到验证码，10秒后再试')
            time.sleep(10)
            code = query_captcha(phone)
        if not is_ok:
            db.update_phone_number(phone, 0)
            continue
        # code = input('请输入收到的验证码：')
        # code = '793351'
        print('正在登录闪动')
        token = http.login_by_sms_code(phone, code)['token']
        '''以下需要一般用户身份'''
        http.set_flash_token(token)
        nickname = db.get_one_nickname()
        print(f'获取用户昵称并更新用户信息：{nickname.name}')
        member = db.get_random_member()

        print('等待一会儿设置用户信息')
        time.sleep(20)
        http.set_user_info(nickname.name, member)
        print('等待一会儿设置密码')
        time.sleep(20)
        print('为账号设置密码......')
        http.set_password('xingzai1982')
        print('保存账号信息......')
        db.create_account(phone, 'xingzai1982', nickname.name, token)

        print('等待一会儿为账号加入俱乐部......')
        time.sleep(20)
        http.join_club(10727)
        # http.join_club(8474)
        print('等待一会儿为用户设置余额......')
        '''以下需要管理员身份'''
        http.set_flash_token(creator_token)
        print('等待20秒给用户设置余额')
        time.sleep(20)
        # member = http.query_club_member(10727, '宇宙第一咸鱼')[0]
        member = http.query_club_member(10727, nickname.name)[0]
        http.set_user_balance(10727, member['memberId'], int(random.random() * 2000) + 5000)
        db.update_phone_number(phone, 1)
        print('账号注册成功，等待3分钟进行下一轮')
        time.sleep(180)
        loop_count = loop_count + 1
